using SimpleJSON;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class SuperAttrHelper : NodeHelper
    {
        public enum Handle
        {
            None,
            RateToSpeed,
            TimeToSpeed
        }

        public Handle handle = Handle.None;
        [SelectRef(UIKey.ATTR_KEY)] public string attrKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey attrDataKey;
        [SelectRef(UIKey.DATA_KEY)] public SelectKey originalAttrDataKey;
        public string originalFormat;
        public string changeFormat;
        public bool pro;
        private Text _Text;
        private TextMeshProUGUI _TextPro;

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        private TextMeshProUGUI TextPro
        {
            get
            {
                if (_TextPro == null) _TextPro = GetComponent<TextMeshProUGUI>();
                return _TextPro;
            }
        }

        protected override BindDataType bindDataType => BindDataType.All;

        protected override void BindData(JSONObject obj)
        {
            var attrData = attrDataKey.Get(obj).AsObject;
            var originalAttrData = originalAttrDataKey.Get(obj).AsObject;
            var data = attrData[attrKey] == null ? 0 : attrData[attrKey].AsInt;
            var original = originalAttrData[attrKey] == null ? 0 : originalAttrData[attrKey].AsInt;
            var change = data != original;

            switch (handle)
            {
                case Handle.TimeToSpeed:
                    if (data != 0) data = 60 / (data / 1000);
                    if (original != 0) original = 60 / (original / 1000);
                    break;
            }

            var tmp = new object[3] { original, data - original, data };
            SetText(string.Format(change ? changeFormat : originalFormat, tmp));
        }

        private void SetText(string t)
        {
            if (pro)
                TextPro.text = t;
            else
                Text.text = t;
        }

        private void SetColor(Color c)
        {
            if (pro)
                TextPro.color = c;
            else
                Text.color = c;
        }
    }
}